package com.jlkf.service.util;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;


import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;

import net.thegreshams.firebase4j.error.FirebaseException;
import net.thegreshams.firebase4j.error.JacksonUtilityException;
import net.thegreshams.firebase4j.model.FirebaseResponse;
import net.thegreshams.firebase4j.service.Firebase;



//fireBase消息通知
public class FireBaseUtil {
	  
	  public static final String PUSHWOOSH_SERVICE_BASE_URL = "https://fcm.googleapis.com/fcm/";
	  //fireBase 发送通知
	   public static String  sendMessageAlert(String userId,String content){
		   String result="";
			 try {
		   HttpURLConnection httpcon = (HttpURLConnection) ((new URL("https://fcm.googleapis.com/fcm/send").openConnection()));
	        httpcon.setDoOutput(true);
	        httpcon.setRequestProperty("Content-Type", "application/json");
	        httpcon.setRequestProperty("Authorization", "key=AAAA0u4bEGw:APA91bFF2dBX9Wo2xTE5f0mbrYheZZNkJ1nxlIyCHgEOPPFA_ROT4eHwSDnhk8qc6hSXObTWyC-91ueWatrOz4rwPjosKJdPy3f1QbrPzTFbR6yHB_0mpye62txZWdKpli-DSgPhEDek");
	        httpcon.setRequestMethod("POST");
	        httpcon.connect();
	        System.out.println("Connected!");
           String cc="{\"notification\":{\"title\": \"fab\", \"text\": \""+content+"\", \"sound\": \"default\"}, \"to\": \""+userId+"\"}"; 
	        byte[] outputBytes = cc.getBytes("UTF-8");
	        OutputStream os = httpcon.getOutputStream();
	        os.write(outputBytes);
	        os.close();
	        // Reading response
	        InputStream input = httpcon.getInputStream();
	        try (BufferedReader reader = new BufferedReader(new InputStreamReader(input))) {
	            for (String line; (line = reader.readLine()) != null;) {
	                System.out.println(line);
	                result+=line;
	            }
	        }
	        System.out.println("Http POST request sent!");
	        return result;
	    } catch (IOException e) {
	        e.printStackTrace();
	        return result;
	    }
	    }
	   //添加途经点 修改目的地
	   public static String  sendMessageAlertAndChangeAddress(String userId,String content){
		   String result="";
			 try {
		   HttpURLConnection httpcon = (HttpURLConnection) ((new URL("https://fcm.googleapis.com/fcm/send").openConnection()));
	        httpcon.setDoOutput(true);
	        httpcon.setRequestProperty("Content-Type", "application/json");
	        httpcon.setRequestProperty("Authorization", "key=AAAA0u4bEGw:APA91bFF2dBX9Wo2xTE5f0mbrYheZZNkJ1nxlIyCHgEOPPFA_ROT4eHwSDnhk8qc6hSXObTWyC-91ueWatrOz4rwPjosKJdPy3f1QbrPzTFbR6yHB_0mpye62txZWdKpli-DSgPhEDek");
	        httpcon.setRequestMethod("POST");
	        httpcon.connect();
	        System.out.println("Connected!");
           String cc="{\"notification\":{\"title\": \"fab\", \"text\": \""+content+"\", \"sound\": \"changeAddress..wav\"}, \"to\": \""+userId+"\"}"; 
	        byte[] outputBytes = cc.getBytes("UTF-8");
	        OutputStream os = httpcon.getOutputStream();
	        os.write(outputBytes);
	        os.close();
	        // Reading response
	        InputStream input = httpcon.getInputStream();
	        try (BufferedReader reader = new BufferedReader(new InputStreamReader(input))) {
	            for (String line; (line = reader.readLine()) != null;) {
	                System.out.println(line);
	                result+=line;
	            }
	        }
	        System.out.println("Http POST request sent!");
	        return result;
	    } catch (IOException e) {
	        e.printStackTrace();
	        return result;
	    }
	    }
	   //新的订单
	   public static String  sendMessageAlertAndSoundOrder(String userId,String content){
		   String result="";
			 try {
		   HttpURLConnection httpcon = (HttpURLConnection) ((new URL("https://fcm.googleapis.com/fcm/send").openConnection()));
	        httpcon.setDoOutput(true);
	        httpcon.setRequestProperty("Content-Type", "application/json");
	        httpcon.setRequestProperty("Authorization", "key=AAAA0u4bEGw:APA91bFF2dBX9Wo2xTE5f0mbrYheZZNkJ1nxlIyCHgEOPPFA_ROT4eHwSDnhk8qc6hSXObTWyC-91ueWatrOz4rwPjosKJdPy3f1QbrPzTFbR6yHB_0mpye62txZWdKpli-DSgPhEDek");
	        httpcon.setRequestMethod("POST");
	        httpcon.connect();
	        System.out.println("Connected!");
           String cc="{\"notification\":{\"title\": \"fab\", \"text\": \""+content+"\", \"sound\": \"trumpety.wav\"}, \"to\": \""+userId+"\"}"; 
	        byte[] outputBytes = cc.getBytes("UTF-8");
	        OutputStream os = httpcon.getOutputStream();
	        os.write(outputBytes);
	        os.close();
	        // Reading response
	        InputStream input = httpcon.getInputStream();
	        try (BufferedReader reader = new BufferedReader(new InputStreamReader(input))) {
	            for (String line; (line = reader.readLine()) != null;) {
	                System.out.println(line);
	                result+=line;
	            }
	        }
	        System.out.println("Http POST request sent!");
	        return result;
	    } catch (IOException e) {
	        e.printStackTrace();
	        return result;
	    }
	    }
	   //用户取消
	   public static String  sendMessageAlertAndSoundCancel(String userId,String content){
		   String result="";
			 try {
		   HttpURLConnection httpcon = (HttpURLConnection) ((new URL("https://fcm.googleapis.com/fcm/send").openConnection()));
	        httpcon.setDoOutput(true);
	        httpcon.setRequestProperty("Content-Type", "application/json");
	        httpcon.setRequestProperty("Authorization", "key=AAAA0u4bEGw:APA91bFF2dBX9Wo2xTE5f0mbrYheZZNkJ1nxlIyCHgEOPPFA_ROT4eHwSDnhk8qc6hSXObTWyC-91ueWatrOz4rwPjosKJdPy3f1QbrPzTFbR6yHB_0mpye62txZWdKpli-DSgPhEDek");
	        httpcon.setRequestMethod("POST");
	        httpcon.connect();
	        System.out.println("Connected!");
           String cc="{\"notification\":{\"title\": \"fab\", \"text\": \""+content+"\", \"sound\": \"driverCancelled.wav\"}, \"to\": \""+userId+"\"}"; 
	        byte[] outputBytes = cc.getBytes("UTF-8");
	        OutputStream os = httpcon.getOutputStream();
	        os.write(outputBytes);
	        os.close();
	        // Reading response
	        InputStream input = httpcon.getInputStream();
	        try (BufferedReader reader = new BufferedReader(new InputStreamReader(input))) {
	            for (String line; (line = reader.readLine()) != null;) {
	                System.out.println(line);
	                result+=line;
	            }
	        }
	        System.out.println("Http POST request sent!");
	        return result;
	    } catch (IOException e) {
	        e.printStackTrace();
	        return result;
	    }
	    }
	   //将需要推送的自定义消息放到firebase数据库中  
	   public static String  postDataForFireBaseDataBase(String uId,String json){
		   //是fireBase中的数据库的访问地址
			String firebase_baseUrl = "https://fabdriverapp.firebaseio.com/user/";
			if( firebase_baseUrl == null || firebase_baseUrl.trim().isEmpty() ) {
				throw new IllegalArgumentException( "Program-argument 'baseUrl' not found but required" );
			}
			// create the firebase
			Firebase firebase;
			try {
				System.out.println(firebase_baseUrl);
				firebase = new Firebase( firebase_baseUrl );
				// "DELETE" (the fb4jDemo-root)
//				FirebaseResponse response = firebase.delete();

				// "PUT" (test-map into the fb4jDemo-root)
//				Map<String, Object> dataMap = new LinkedHashMap<String, Object>();
//				dataMap.put( "user1", "This was PUT into the fb4jDemo-root" );
//				dataMap.put( "user2", json);
				//{ "orderId":110,"type":1,"status":20 }}
				FirebaseResponse response = firebase.post( uId, json );//拼接出来的url是 firebase_baseUrl+uId+".json"  如：https://fabdriverapp.firebaseio.com/226.json
				System.out.println( "\n\nResult of POST (for the test-POST):\n" + response );
				System.out.println("\n");
				return response.getRawBody();
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return "UnsupportedEncodingException";
			}  catch (FirebaseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return "FirebaseException";
			}
	   }
	   public static void main(String[] args) {
		   try {
			System.out.println(getAccess());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	  
	   
	   //访问数据库获取的token方法
	   public static String getAccess() throws IOException{
			
		   String uu=FireBaseUtil.class.getResource("").getPath().toString().replace("/", System.getProperty("file.separator"));
		   System.out.println("uuuuuuuu========="+uu);
		   String  path2 = uu.split("fab_api")[0]+"fab_api"+System.getProperty("file.separator")+"firebaseDataBase"+System.getProperty("file.separator")+"fabdriverapp-firebase-adminsdk-ou2ng-f7fe56a315.json";
			System.out.println("firebase____json_____url==="+path2);
			
			// Load the service account key JSON file
			FileInputStream serviceAccount = new FileInputStream(path2);

			// Authenticate a Google credential with the service account
			GoogleCredential googleCred = GoogleCredential.fromStream(serviceAccount);

			
			// Add the required scopes to the Google credential
			GoogleCredential scoped = googleCred.createScoped(
			    Arrays.asList(
			      "https://www.googleapis.com/auth/firebase.database",
			      "https://www.googleapis.com/auth/userinfo.email"
			    )
			);

			// Use the Google credential to generate an access token
			scoped.refreshToken();
			String token = scoped.getAccessToken();
			// See the "Using the access token" section below for information
			// on how to use the access token to send authenticated requests to the
			// Realtime Database REST API.
			return token;

			
		}
}



